<template>
  <AModal
    v-model:visible="visible"
    unmount-on-close
    :title="modalTitle"
    :width="importConfig?.width"
    v-bind="importConfig?.modalAttr"
    :mask-closable="maskClosable"
    :on-before-ok="handleBeforeOk"
    :ok-loading="okBtnLoading"
  >
    <div v-if="!progress.msg" class="import-container">
      <div>
        <a-upload
          ref="upload"
          v-model:file-list="fileList"
          :limit="1"
          :auto-upload="false"
          accept=".xlsx, .xls"
          :headers="headers"
          draggable
          :action="upLoadUrl"
          :show-remove-button="showRemoveButton"
          @change="handleUploadChange"
          @progress="handleUploadProgress"
          @success="handleUploadSuccess"
          @error="handleUploadError"
        >
        </a-upload>
        <a-progress v-if="progress.status !== 0" :percent="progress.percent" />
      </div>
      <div class="import-container-tisp">
        <p
          ><a-checkbox v-model="checked" value="1"></a-checkbox
          >是否更新已经存在的用户数据
        </p>
        <p
          >仅允许导入xls、xlsx格式文件。
          <span
            v-if="importConfig.template"
            class="template"
            @click="getTemplate"
            >下载模板</span
          >
        </p>
      </div>
    </div>
    <div v-else id="msg"></div>
  </AModal>
</template>

<script lang="ts">
  import { Message } from '@arco-design/web-vue';
  import { defineComponent, ref, computed, nextTick, watch } from 'vue';
  import { getToken } from '@/utils/auth';
  import { dataToUrlParams } from '@/utils/index';

  export default defineComponent({
    props: {
      importConfig: {
        type: Object,
        default: () => ({
          modalAttr: {},
          width: '500px',
          title: '导入',
          url: `${import.meta.env.VITE_API_BASE_URL}/system/user/importData`,
          template: null,
        }),
      },
      refresh: {
        type: Boolean,
        default: false,
      },
    },
    emits: ['update:refresh'],
    setup(props, { emit }) {
      const upload = ref();
      const visible = ref(false);
      const checked = ref(false);
      const fileList: any = ref([]);
      const uploadData = ref({});
      const okBtnLoading = ref(false);
      const showRemoveButton = ref(true);
      const headers = ref({
        Authorization: `Bearer ${getToken()}`,
      });
      const progress = ref({
        status: 0,
        percent: 0,
        msg: null,
      });

      const upLoadUrl = computed(() => {
        return `${props.importConfig?.url}${dataToUrlParams({
          updateSupport: checked.value ? true : 0,
        })}`;
      });
      const modalTitle = computed(() => {
        return progress.value.msg ? '导入结果' : props.importConfig.title;
      });
      const handleBeforeOk = (done: (closed: boolean) => void) => {
        if (progress.value.msg) {
          done(true);
        }
        if (fileList.value.length > 0) {
          showRemoveButton.value = false;
          upload.value.submit();
          done(false);
          progress.value.status = 200;
          okBtnLoading.value = true;
        } else {
          Message.warning('请选择文件');
          done(false);
        }
      };
      const handleUploadChange = (fileItems: any) => {
        let files: any[] = [];
        if (fileItems.length > 0) {
          files = [fileItems[fileItems.length - 1]];
        }
        fileList.value = files;
      };
      const handleUploadProgress = (fileItem: any) => {
        progress.value.percent = fileItem.percent;
      };
      const handleUploadSuccess = (fileItem: any) => {
        progress.value.msg = fileItem.response.msg;
        // eslint v-html xss 报错
        const devDom: any = document.createElement('div');
        devDom.innerHTML = progress.value.msg;
        nextTick(() => {
          document.getElementById('msg')?.appendChild(devDom);
        });
        okBtnLoading.value = false;
      };
      const handleUploadError = (fileItem: any) => {
        progress.value.msg = fileItem.response.msg;
        // eslint v-html xss 报错
        const devDom: any = document.createElement('div');
        devDom.innerHTML = progress.value.msg;
        nextTick(() => {
          document.getElementById('msg')?.appendChild(devDom);
        });
        okBtnLoading.value = false;
      };
      const open = () => {
        visible.value = true;
        checked.value = false;
        fileList.value = [];
        okBtnLoading.value = false;
        progress.value = {
          status: 0,
          percent: 0,
          msg: null,
        };
      };
      const getTemplate = () => {
        const { importConfig } = props;
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        importConfig.template({}, () => {});
      };
      watch(
        () => visible,
        (val: any) => {
          if (val.value === false) {
            emit('update:refresh', true);
          }
        },
        {
          deep: true,
          // immediate: true,
        }
      );
      return {
        upload,
        headers,
        upLoadUrl,
        visible,
        maskClosable: true,
        checked,
        fileList,
        uploadData,
        progress,
        showRemoveButton,
        okBtnLoading,
        modalTitle,
        open,
        handleBeforeOk,
        handleUploadChange,
        dataToUrlParams,
        handleUploadProgress,
        handleUploadSuccess,
        handleUploadError,
        getTemplate,
      };
    },
  });
</script>

<style lang="less" scoped>
  .import-container {
    :deep(.arco-upload-progress) {
      display: none;
    }
    &-tisp {
      margin: 10px auto;
      text-align: center;
      a {
        text-decoration: none;
      }
      p {
        margin-block-end: 0em;
        margin-block-start: 0em;
        display: flex;
        justify-content: center;
        :deep(.arco-checkbox) {
          margin-right: 5px;
        }
        .template {
          color: rgb(67, 112, 248) !important;
          cursor: pointer;
        }
      }
    }
  }
  #msg {
    overflow: auto;
    max-height: 600px;
  }
</style>
